import access from '@/access';
import type { FormItem } from '@/components/FormDialog/data';
import ToeForm from '@/components/FormDialog/index';
import ToeUpload from '@/components/UploadDialog/index';
import {
  getMRPModuleByPage,
  addMRPModule,
  updateMRPModule,
  delMRPModule,
  getMRPModuleList,
} from '@/services/drivepara/MRPmodule';
import { PlusOutlined } from '@ant-design/icons';
import { PageContainer } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, message, Modal, Select, Tag } from 'antd';

import { Spin } from 'antd';
import type { SelectProps } from 'antd/es/select';
import debounce from 'lodash/debounce';
import React, { useMemo, useRef, useState } from 'react';
import { useAccess, useLocation } from 'umi';
// const { Option } = Select;

const MRPmodule: React.FC<{}> = () => {
  const [formTitle, setFormTitle] = useState('New log');
  const actionRef = useRef<ActionType>();
  const [formVisit, setFormVisit] = useState(false);
  const [formDisabled, setFormDisabled] = useState(false); //设置表单禁用
  const access = useAccess();
  const formRef = useRef(null);
  const [rowData, setRowData] = useState({ id: '' }); // 保存行值
  const [deleteVisit, setDeleteVisit] = useState(false); // 删除提示框
  const [isCreate, setIsCreate] = useState(false);

  const columns: ProColumns[] = [
    {
      title: 'index',
      dataIndex: 'index',
      valueType: 'index',
      width: 60,
    },
    {
      title: 'identification',
      search: false,
      hideInTable: true,
      dataIndex: 'identification',
      width: 150,
    },
    {
      title: 'item code',
      dataIndex: 'itemCode',
      valueType: 'select',
      valueEnum: {
        1: 'test 1',
        2: 'test 2',
        3: 'test 3',
      },
      width: 100,
    },
    {
      title: 'batch',
      // search: false,
      dataIndex: 'batch',
      width: 110,
    },
    {
      title: 'order multiples',
      // search: false,
      dataIndex: 'orderMultiples',
      width: 120,
    },
    {
      title: 'safe stock',
      // search: false,
      dataIndex: 'safeStock',
      width: 120,
    },
    {
      title: 'gross requirement',
      // search: false,
      dataIndex: 'grossRequirement',
      width: 120,
    },
    {
      title: 'net requirement',
      // search: false,
      dataIndex: 'netRequirement',
      width: 120,
    },
    {
      title: '创建人', //表头显示的名称
      // search: false,
      dataIndex: 'createName',
      width: 80,
    },
    {
      title: '创建时间', //表头显示的名称
      // search: false,
      dataIndex: 'createDate',
      width: 150,
    },

    {
      title: 'operation',
      align: 'center',
      sorter: true,
      valueType: 'option',
      key: 'option',
      fixed: 'right',
      render: (text, record, _, action) => {
        const buttonList = [];
        if (access.canAdmin() || access.canChiefEngineer()) {
          buttonList.push(
            <a
              key="editKey"
              onClick={() => {
                formRef.current.setFieldsValue({
                  ...record,
                });
                setFormTitle('edit log');
                setFormDisabled(true);
                setFormVisit(true);
              }}
            >
              edit
            </a>,
          );

          buttonList.push(
            <a
              key="deleteKey"
              onClick={() => {
                Modal.confirm({
                  title: 'Delete MRP log',
                  content: 'R u sure to delete MRP log?',
                  okText: 'Yes',
                  cancelText: 'No',
                  onOk: async () => {
                    await delMRPModule({ id: record.id });
                    actionRef.current?.reload();
                  },
                });
              }}
            >
              delete
            </a>,
          );
        }

        return buttonList;
      },
    },
  ];
  const formColumns: FormItem[] = [
    { field: 'id', label: 'id', hidden: true },
    { field: 'identification', label: 'identification', hidden: true },
    {
      field: 'itemCode',
      label: 'item code',
      type: 'select',
      // disabled: true,
      options: [
        { value: 1, label: 'test 1' },
        { value: 2, label: 'test 2' },
        { value: 3, label: 'test 3' },
      ],
    },
    {
      field: 'batch',
      label: 'batch',
      type: 'inputNumber',
      value: 1,
      // disabled: true,
    },
    {
      field: 'orderMultiples',
      label: 'order multiples',
      // disabled: true,
    },
    {
      field: 'safeStock',
      label: 'safe stock',
      type: 'inputNumber',
      value: 0,
      // disabled: true,
    },
    {
      field: 'grossRequirement',
      label: 'gross requirement',
      type: 'inputNumber',
      value: 0,
      // disabled: true,
    },
    {
      field: 'netRequirement',
      label: 'net requirement',
      type: 'inputNumber',
      value: 0,
      // disabled: true,
    },
  ];

  const handleSubmit = async () => {
    if (formTitle == 'New log') {
      await addMRPModule(formRef.current.getFieldsValue());
    } else {
      await updateMRPModule(formRef.current.getFieldsValue());
    }
    setFormVisit(false);
    actionRef.current.reload();
    message.success('Add successfully!');
  };

  return (
    <PageContainer>
      <ProTable
        headerTitle="MRP form"
        actionRef={actionRef}
        rowKey="id"
        toolBarRender={(action, { selectedRows, selectedRowKeys }) => {
          return [
            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                formRef.current.resetFields();
                setFormDisabled(false);
                setFormVisit(true);
                setFormTitle('New log');
              }}
              type="primary"
            >
              New
            </Button>,

            <Button
              key="button"
              icon={<PlusOutlined />}
              onClick={() => {
                Modal.confirm({
                  title: 'Delete log',
                  content: 'R u sure to delete log?',
                  okText: 'Yes',
                  cancelText: 'No',
                  onOk: async () => {
                    await delMRPModule(selectedRowKeys);
                    actionRef.current.reload();
                  },
                });
              }}
              type="primary"
            >
              Delete
            </Button>,
          ];
        }}
        request={async (params = {}, sort, filter) => {
          const result = await getMRPModuleByPage(params);
          console.log(result);
          return {
            data: result.data.content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        columns={columns}
        rowSelection={{}}
        scroll={{ x: 2000, y: 350 }}
      />

      <ToeForm
        visible={formVisit}
        title="New log"
        disabled={formDisabled}
        ref={formRef}
        initialValues={{
          batch: 1,
          safeStock: 0,
          grossRequirement: 0,
          netRequirement: 0,
        }}
        columns={formColumns}
        onCancel={() => {
          setFormVisit(false);
        }}
        onOk={handleSubmit}
      />
    </PageContainer>
  );
};

export default MRPmodule;
